package com.lechi.web.framework.log;

import com.alibaba.fastjson2.JSON;
import com.lechi.web.common.utils.SecurityUtils;
import com.lechi.web.common.utils.spring.SpringUtils;
import com.lechi.web.system.domain.IotOperLog;
import com.lechi.web.system.service.IIotOperLogService;

import java.util.Date;
import java.util.TimerTask;

public class IotExceptionLog {

    /**
     * 记录异常日志
     *
     * @param e          异常
     * @param title      标题
     * @param methodName 方法名
     * @param param      参数
     * @param <T>        入参和出参
     * @return timertask
     */
    @SafeVarargs
    public static <T> TimerTask exceptionLog(final Exception e, String title, String methodName, final T... param) {
        final IotOperLog iotOperLog = new IotOperLog();
        iotOperLog.setTitle(title);
        String userName = "";
        try {
            userName = SecurityUtils.getUsername();
        } catch (Exception ignored) {

        }
        iotOperLog.setOperator(userName);
        iotOperLog.setParam(param.length > 0 ? JSON.toJSONString(param[0]) : "");
        iotOperLog.setResponse(param.length > 1 ? JSON.toJSONString(param[1]) : "");
        iotOperLog.setErrorMsg(e.getMessage());
        iotOperLog.setStatus(1L);
        iotOperLog.setMethod(methodName);
        iotOperLog.setOperTime(new Date());
        return new TimerTask() {
            @Override
            public void run() {
                SpringUtils.getBean(IIotOperLogService.class).insertIotOperLog(iotOperLog);
            }
        };
    }


}
